import React, { memo, useState } from 'react';

import { Button, message } from 'antd';
import { Input } from 'antd';
import { useDispatch } from 'react-redux';

import { getAddAction } from '../store/actionCreators';

export default memo(function Footer() {
  // redux hooks

  const dispatch = useDispatch();

  // orter hooks
  const [isAdd, setIsAdd] = useState(false);
  const [addVal, setAddval] = useState('');

  // function
  // 添加内容
  function addToDoListChange() {
    if (!addVal) {
      message.error('添加的内容不能为空');
      return false;
    }
    const addItem = {
      id: Math.random().toString(32).slice(2), // 随机id
      content: addVal,
      isComplete: false
    };
    dispatch(getAddAction(addItem));
    setIsAdd(false);
    setAddval('');
    message.success('添加成功');
  }

  let addBtn = (
    <Button type="primary" onClick={() => setIsAdd(true)}>
      新增
    </Button>
  );
  let addComponent = (
    <div style={{ display: 'flex' }}>
      <Input
        onChange={(e) => setAddval(e.target.value.trim())}
        style={{ marginRight: '10px' }}
        value={addVal}
      />
      <Button type="primary" onClick={() => addToDoListChange()}>
        确认
      </Button>
    </div>
  );
  let component = isAdd ? addComponent : addBtn;
  return <div style={{ marginTop: '10px' }}>{component}</div>;
});
